""" 与用户相关的视图 """

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated

from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt

# 导入用户模型
from sa.models import User
# 导入序列化器
from sa.serializers.accountSerializer import (
    UserLoginSerializer,
    UserInfoSerializer, UserAllInfoSerializer)

import logging

# 日志记录对象
logger = logging.getLogger('django')


# 类视图，你应该使用 method_decorator 来将 CSRF 豁免应用于特定的方法（如 dispatch 方法，
# 它处理所有 HTTP 方法，或者仅应用于 post 方法）
@method_decorator(csrf_exempt, name='dispatch')
class UserLoginGenericAPIView(GenericAPIView):
    # serializer_class, 指定序列化器类
    serializer_class = UserLoginSerializer

    # queryset, 查询集
    # queryset = User.objects.all()

    def post(self, request):
        serializer = self.get_serializer(data=request.data)
        # print(request.data)
        serializer.is_valid(raise_exception=True)
        # 序列化器传过来的 attrs['user'] = user 是一个对象，不能直接序列化
        # 手动将 User 对象转换为字典,需要的字段
        user = serializer.validated_data.get('user')
        # 处理 roles 多对多字段
        #  将 QuerySet 转换为包含字典的 QuerySet。 values('id', 'role_name')需要值
        # users_roles = user.roles.all().values('id', 'role_name')
        # 再转成列表包字典
        # role_list = list(users_roles)
        user_info = {
            'id': user.id,
            'username': user.username,
            'cn_name': user.cn_name,
            'region': user.region,
            'token': user.token,
            # 'roles': role_list
        }
        # 记录日志
        logger.info(f"当前登录用户名为：{user_info['username']}")
        return Response(data=user_info, status=status.HTTP_200_OK)


class UserAllInfoGenericAPIView(GenericAPIView):
    """获取所有用户的接口"""
    # 指定序列化器
    serializer_class = UserAllInfoSerializer
    # 查询集
    queryset = User.objects.exclude(username='admin')

    def get(self, request):
        user_list = self.get_queryset()
        serializer = self.get_serializer(instance=user_list, many=True)
        return Response(data=serializer.data)


class UserInfoGenericAPIView(GenericAPIView):
    """个人信息获取和密码修改"""
    # 指定序列化器类
    serializer_class = UserInfoSerializer
    # 指定查询集
    queryset = User.objects.all()
    # 指定只有经过认证的用户才能访问该视图或视图集
    permission_classes = [IsAuthenticated]

    def get(self, request, pk):
        obj = self.get_object()
        serializer = self.get_serializer(instance=obj)
        if obj.id != request.user.id:
            return Response({"error": "只能查看自己的信息"}, status=status.HTTP_403_FORBIDDEN)
        # print(serializer.data['username'])
        logger.info(f"成功获取个人信息：{serializer.data['username']},{serializer.data['cn_name']}")
        return Response(data=serializer.data)

    def put(self, request, pk):
        # 获取并验证用户
        user = self.get_object()
        if user.id != request.user.id:
            return Response({"error": "只能修改自己的密码"}, status=status.HTTP_403_FORBIDDEN)
        # 验证数据
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 获取并设置新密码
        new_password = serializer.validated_data.get('password2')
        user.set_password(new_password)
        user.save()
        # 记录安全日志
        logger.info(f"用户 {user.cn_name} 修改密码成功!")
        return Response(data={"message": "密码修改成功"}, status=status.HTTP_200_OK)


class UserInfoRegionChoicesAPIView(APIView):
    """ 用户列表的 region choices 信息 """

    def get(self, request):
        region_choices = User._meta.get_field('region').choices
        # print(region_choices)
        options = ([{"value": None, 'label': '区域'}] +
                   [{'value': value, "label": label} for value, label in region_choices])
        # print(options)
        return Response(data=options)
